<?php

namespace app\admin\controller\order;

use app\admin\model\Organization;
use app\admin\model\Bin;
use app\admin\model\bin\History;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use app\common\library\ValidatorSn;
use think\Session;


/**
 * 采购入库
 *
 * @icon fa fa-circle-o
 */
class Purchase extends Backend
{

    /**
     * Purchase模型对象
     * @var \app\admin\model\order\Purchase
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Purchase;
        $this->view->assign("purchaseTypeList", $this->model->getPurchaseTypeList());
        $this->view->assign("binTypeList", $this->model->getBinTypeList());
        $this->view->assign("binNativeList", $this->model->getBinNativeList());
        $this->view->assign("currencyTypeList", $this->model->getCurrencyTypeList());
        $this->view->assign("yardList", $this->model->yardList());
    }



    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            $pathinfo=input('server.PATH_INFO');
            $purchase_type=0;
            if($pathinfo=='/order/purchase/index/purchase_type/1'){
                $purchase_type=1;
            }elseif ($pathinfo=='/order/purchase/index/purchase_type/2'){
                $purchase_type=2;
            }

            $this->assign("purchase_type",$purchase_type);

            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with([
                'type'=>function($query){$query->withField('name');},
                'native'=>function($query){$query->withField('name');},
                'bincompany'=>function($query){$query->withField('organ_name');},
                'ourcompany'=>function($query){$query->withField('organ_name');},
                'yard'=>function($query){$query->withField('organ_name');},
                'admin'=>function($query){$query->withField('nickname');},
            ])
            ->where($where)
            ->order(['createtime'=>'desc'])
            ->paginate($limit);
        $lists=$list->toArray();
        $data=$lists['data'];
        foreach ($data as &$v){
/*            $v['createtime']=date('Y-m-d',$v['createtime']);*/
            $v['purchasetime']=date('Y-m-d',$v['purchasetime']);
            $v['deadlinetime']=date('Y-m-d',$v['deadlinetime']);
            $v['remark']=strip_tags($v['remark']);
            $remark_res=db('remark')->where(['correspond_id'=>$v['id'],'type'=>1])->order(['createtime'=>'desc'])->find();
            $v['remark_total_nuber']=db('remark')->where(['correspond_id'=>$v['id'],'type'=>1])->count();
            $v['last_remark']='';
            if(!empty($remark_res['remark_content'])){
                $v['last_remark']=date('Y-m-d',$remark_res['createtime']).':'.strip_tags($remark_res['remark_content']);
            }

        }


        $result = array("total" => $lists['total'], "rows" => $data);


        return json($result);

    }
    /**
     * 租箱入库
     *
     * @return string
     * @throws \think\Exception
     */
    public function rent_add()
    {
        if (false === $this->request->isPost()) {
            /*            $yardList=Organization::getYard();*/
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['purchasetime']=strtotime($params['purchasetime']);
        $params['deadlinetime']=strtotime($params['deadlinetime']);
        $params['createtime']=time();
        $params['purchase_type']=2;
        $params['purchase_sn']='P'.substr(md5(microtime(true)), 0, 9);
        $binHistoty=[];
        $binData=[];
        $remark=[];
        if(!empty($params['multiplejson'])){
            $binData=$params['multiplejson'];
            unset($params['multiplejson']);
        }
        $params['complete_number']=count($binData);
        if($params['complete_number']==$params['purchase_number']){
            $params['is_finish']=1;
        }elseif ($params['complete_number']>$params['purchase_number']){
            $this->error('箱子数量已超过计划数量!');
        }
        $validateSn= new ValidatorSn();

        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->insertGetId($params);
            if(!empty($params['remark'])){
                $remark['correspond_id']=$result;
                $remark['remark_content']=$params['remark'];
                $remark['user_id']= Session::get('admin.id');
                $remark['type'] = 1;
                $remark['createtime'] = time();
                $remarkRes= Db::name('remark')->insert($remark);
            }

            $validate=\think\Loader::validate('Bin');
            if(!empty($binData)) {

                foreach ($binData as &$vo) {
                    if (!$validate->check($vo)) {
                        $this->error($vo['bin_sn'] . $validate->getError());
                    }

                    if(!$validateSn->isValid($vo['bin_sn'])){
                        $this->error($vo['bin_sn'].'集装箱号无效!');
                    }

                    $vo['order_id'] = $result;
                    $vo['bin_company_id'] = $params['bin_company_id'];
                    $vo['our_company_id'] = $params['our_company_id'];
                    $vo['origin_sn'] = $params['purchase_sn'];
                    $vo['bin_origin'] = 2;
                    if (!empty($vo['entertime'])) {
                        $vo['firstentertime'] = strtotime($vo['entertime']);
                    }
                    $vo['createtime'] = time();
                    $vo['remark'] = $vo['bin_remark'];
                    $vo['current_status'] = 1;
                    $vo['last_status'] = 2;
                    $vo['return_city'] = $params['return_city'];
                    $vo['weigh'] = '';
                }
                $bin = new Bin();
                $res = $bin->allowField(true)->saveAll($binData);
                if ($res) {
                    $json = json_encode((object)$res);
                    $binResLists = json_decode($json, true);
                    foreach ($binResLists as $k => &$vv) {
                        $binHistoty[$k]['bin_id'] = (int)$vv['id'];
                        $binHistoty[$k]['receipt'] = $vv['origin_sn'];
                        $binHistoty[$k]['organization_id'] = (int)$vv['our_company_id'];
                        $binHistoty[$k]['business_type'] = 2;
                        $binHistoty[$k]['organ_type'] = 2;
                        $binHistoty[$k]['yard_id'] = (int)$vv['yard_id'];
                        if (!empty($vv['firstentertime'])) {
                            $binHistoty[$k]['entertime'] = $vv['firstentertime'];
                        }
                        $binHistoty[$k]['createtime'] = time();

                    }

                }

                $history = new History();
                $historyRes = $history->allowField(true)->saveAll($binHistoty);
            }

            Db::commit();

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     *买箱入库
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
/*            $yardList=Organization::getYard();*/
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['createtime']=time();
        $params['purchasetime']=strtotime($params['purchasetime']);
        $params['purchase_type']=1;
        $params['purchase_sn']='P'.substr(md5(microtime(true)), 0, 9);
        $remark=[];
        $binHistoty=[];
        $binData=[];
        if(!empty($params['multiplejson'])){
            $binData=$params['multiplejson'];
            unset($params['multiplejson']);
        }
        $params['complete_number']=count($binData);
        if($params['complete_number']==$params['purchase_number']){
            $params['is_finish']=1;
        }elseif ($params['complete_number']>$params['purchase_number']){
            $this->error('箱子数量已超过计划数量!');
        }
        $validateSn= new ValidatorSn();
        $result = false;
        Db::startTrans();
        try {

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->insertGetId($params);
            if(!empty($params['remark'])){
                $remark['correspond_id']=$result;
                $remark['remark_content']=$params['remark'];
                $remark['user_id']= Session::get('admin.id');
                $remark['type'] = 1;
                $remark['createtime'] = time();
                $remarkRes= Db::name('remark')->insert($remark);
            }
            $validate = \think\Loader::validate('Bin');

            if(!empty($binData)){
                foreach ($binData as &$vo){
                    if (!$validate->check($vo)) {
                        $error=$validate->getError();
                        $this->error($vo['bin_sn'].$error);
                    }
                    if(!$validateSn->isValid($vo['bin_sn'])){
                        $this->error($vo['bin_sn'].'集装箱号无效!');
                    }
                    $vo['order_id']=$result;
                    $vo['bin_company_id']=$params['bin_company_id'];
                    $vo['our_company_id']=$params['our_company_id'];
                    $vo['origin_sn']=$params['purchase_sn'];
                    $vo['bin_origin']=1;
                    $vo['createtime']=time();
                    if(!empty($vo['entertime'])){
                        $vo['firstentertime']=strtotime($vo['entertime']);
                    }
                    $vo['remark']=$vo['bin_remark'];
                    $vo['current_status']=1;
                    $vo['last_status']=1;
                    $vo['weigh']='';
                }
                $bin=new Bin();
                $res= $bin->allowField(true)->saveAll($binData);

                if($res){
                    $json = json_encode((object)$res);
                    $binResLists = json_decode($json, true);
                    foreach ($binResLists as $k=> &$vv){
                        $binHistoty[$k]['bin_id']=(int)$vv['id'];
                        $binHistoty[$k]['receipt']=$vv['origin_sn'];
                        $binHistoty[$k]['organization_id']=(int)$vv['our_company_id'];
                        $binHistoty[$k]['business_type']=1;
                        $binHistoty[$k]['organ_type']=2;
                        $binHistoty[$k]['yard_id']=(int)$vv['yard_id'];
                        if(!empty($vv['firstentertime'])){
                            $binHistoty[$k]['entertime']=$vv['firstentertime'];
                        }
                        $binHistoty[$k]['createtime']=time();

                    }

                }
                $history=new History();
                $historyRes= $history->allowField(true)->saveAll($binHistoty);

            }

            Db::commit();

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

/*
 *    添加箱子
 */

    public function add_bin($ids = null){
        $row = $this->model->get($ids);
         $purchase_type= input('purchase_type');
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $row= $row->toArray();
        $row['remain_number']=$row['purchase_number']-$row['complete_number'];
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $binData=$params['multiplejson'];
        $validateSn= new ValidatorSn();
        $result = false;
        Db::startTrans();
        try {

            $validate = \think\Loader::validate('Bin');

            if(!empty($binData)){
                foreach ($binData as &$vo){
                    if (!$validate->check($vo)) {
                        $error=$validate->getError();
                        $this->error($vo['bin_sn'].$error);
                    }
                    if(!$validateSn->isValid($vo['bin_sn'])){
                        $this->error($vo['bin_sn'].'集装箱号无效!');
                    }
                    $vo['order_id']=$ids;
                    $vo['bin_company_id']=$row['bin_company_id'];
                    $vo['our_company_id']=$row['our_company_id'];
/*                    $vo['bin_type']=$row['bin_type'];*/
                    $vo['origin_sn']=$row['purchase_sn'];
                    if($purchase_type==2){
                        $vo['bin_origin']=2;
                    }
                    $vo['createtime']=time();
                    if(!empty($vo['entertime'])){
                        $vo['firstentertime']=strtotime($vo['entertime']);
                    }
                    $vo['remark']=$vo['bin_remark'];
                    $vo['current_status']=1;
                    $vo['last_status']=1;
                    $vo['weigh']='';
                }
                $bin=new Bin();
                $res= $bin->allowField(true)->saveAll($binData);

                if($res){
                    $json = json_encode((object)$res);
                    $binResLists = json_decode($json, true);
                    foreach ($binResLists as $k=> &$vv){
                        $binHistoty[$k]['bin_id']=(int)$vv['id'];
                        $binHistoty[$k]['receipt']=$vv['origin_sn'];
                        $binHistoty[$k]['organization_id']=(int)$vv['our_company_id'];
                        $binHistoty[$k]['business_type']=1;
                        $binHistoty[$k]['organ_type']=2;
                        $binHistoty[$k]['yard_id']=(int)$vv['yard_id'];
                        if(!empty($vv['firstentertime'])){
                            $binHistoty[$k]['entertime']=$vv['firstentertime'];
                        }
                        $binHistoty[$k]['createtime']=time();

                    }

                }
                $history=new History();
                $historyRes= $history->allowField(true)->saveAll($binHistoty);
                $changeParam=[];
                $changeParam['complete_number']=$row['complete_number']+count($binData);
                if($changeParam['complete_number']==$row['purchase_number']){
                    $changeParam['is_finish']=1;
                } elseif ($changeParam['complete_number']>$row['purchase_number']){
                    $this->error('箱子数量已超过计划数量!');
                }

                $result = $this->model->allowField(true)->save($changeParam,['id'=>$ids]);

            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }
}
